const app = getApp();
const QuoteApi = require('../../../api/quote.js');
const InfoApi = require('../../../api/information.js');
const UserApi = require('../../../api/user.js');
var {quotationColumns} = require('../../../utils/data.js');
const query = wx.createSelectorQuery();
const util = require('../../../utils/util.js')
const commonUtil = require('../../../utils/common.js')

Page({
  data: {
    currentMenu: null,
    currentSub: null,
    menuList: [],
    subList: [],
    ableView: true,
    tableInfo: {
      columns: [],
      data: []
    },
    modalContent: {
      title: null, content: null
    },
    currentQuoteGroupId: null,
    _optionData: {
      currentMenuId: null
    },
    _globalData: null,
    dialogVisible: false,
    customerDialogVisible: false,
    reload: false,
    userInfo: wx.getStorageSync('userInfo')
  },
  
  onLoad(options){
    console.log(options);
    if (options.currentMenuItemId) {
      this.setData({_optionData: options})
    }
  },

  onShow() {
    this.initData(this.data._optionData)
  },
  onUnload() {
    console.log('onunload');
    // wx.removeStorageSync('currentMenuItem')
    // wx.removeStorageSync('currentMenuItemList')
    let _currentQuote = wx.getStorageSync('currentQuote');
    console.log(_currentQuote);
    if (!_currentQuote) {
      wx.removeStorageSync('currentMenu')
      wx.removeStorageSync('currentSub')
      wx.removeStorageSync('detailBack')
    }
  },
  initData(options){
    let _currentMenuItem, _currentMenuItemList;
    if (options.currentMenuItemId) {
      this.getFrontPageLocationList();
      setTimeout(()=>{
        let _menuGroupList = wx.getStorageSync('menuGroupList');
        if (_menuGroupList != undefined) {
          let isExist = _menuGroupList.find(i=>i.menuId == options.currentMenuItemId);
          if (isExist) {
            _currentMenuItem = isExist;
            this.getFrontMenuList(isExist.menuId)
          }
        }
      }, 300)
    } else {
      _currentMenuItem = wx.getStorageSync('currentMenuItem');
    }

    let token = wx.getStorageSync('token');
    let tokenExpire = wx.getStorageSync('tokenExpire');
    let currentTime = new Date().getTime();
    if (token && currentTime - new Date(tokenExpire).getTime() > 0) {
      commonUtil.getUserServiceState();
    }
    setTimeout(()=>{
      _currentMenuItemList = wx.getStorageSync('currentMenuItemList');

      let userService = wx.getStorageSync('userService');
      let detailBack = wx.getStorageSync('detailBack');
      let _subListChilds = [];
      let _currentMenu = null;
      let _currentSub = null;
      let _currentQuoteGroupId = null;
      console.log(options);
      console.log(_currentMenuItem);
      console.log(_currentMenuItemList);
      console.log('detailBack: ', detailBack);
  
      if (_currentMenuItemList) {
        if (_currentMenuItemList.length>0) {
          if (detailBack) {
            _currentMenu = wx.getStorageSync('currentMenu');
            _currentSub = wx.getStorageSync('currentSub');
            console.log(_currentMenu);
            console.log(_currentSub);

            if (_currentMenu['children']) {
              _subListChilds = _currentMenu['children'];
            }
            if (_currentMenu.associated) {
              _currentQuoteGroupId = _currentMenu['quoteGroupId'];
            } else {
              if (_currentSub && _currentSub.associated) {
                _currentQuoteGroupId = _currentSub['quoteGroupId'];
              }
            }
          } else {
            if (!options.currentMenuId) {
              _currentMenu = _currentMenuItemList[0];
    
              if (_currentMenuItemList[0]['children']) {
                _subListChilds = _currentMenuItemList[0]['children'];
              }
              _currentSub = _subListChilds && _subListChilds.length > 0 ? _subListChilds[0] : null;
    
              if (_currentMenuItemList[0]['associated']) {
                _currentQuoteGroupId = _currentMenuItemList[0]['quoteGroupId'];
              } else {
                if (_subListChilds.length > 0) {
                  if (_subListChilds[0]['associated']) {
                    _currentQuoteGroupId = _subListChilds[0]['quoteGroupId'];
                  } else {
                    _currentQuoteGroupId = null;
                  }
                } else {
                  _currentQuoteGroupId = null;
                }
              }
            } else {
              _currentQuoteGroupId = options.currentQuoteGroupId;
    
              let item = _currentMenuItemList.find(i=>i.menuId==options.currentMenuId);
              console.log(item);
              if (item) {
                _currentMenu = item;
                _subListChilds = item['children'];
                if (_subListChilds && _subListChilds.length > 0) {
                  let sub = _subListChilds.find(v=>v.menuId==options.currentSubId);
                  console.log(sub);
                  _currentSub = sub ? sub : null;
                }
              }
            }
          }
        } else {
          _currentMenu = null;
        }
      }
      wx.setNavigationBarTitle({title: _currentMenuItem.itemName});
  
      this.setData({
        ['_globalData.token']: token,
        ['_globalData.userService']: userService,
        ['_globalData.fsUrl']: app.globalData.fsUrl,
        menuList: _currentMenuItemList,
        subList: _subListChilds,
        currentMenu: _currentMenu,
        currentSub: _currentSub,
        currentQuoteGroupId: _currentQuoteGroupId,
      })
      setTimeout(()=>{
        let _ableView = this.getAbleView();
        
        if (_ableView) {
          this.getGroupColumnListByQuoteGroupId(this.data.currentQuoteGroupId);
        }
        this.setData({
          ableView: _ableView
        })
      }, 200)
  
      if (token) {
        if (userService) {
          this.getModalContent()
          if (['expire', 'expiring'].includes(userService.state) && _currentMenuItem.needPay == true) {
            this.setData({dialogVisible: true})
            setTimeout(()=>{
              this.setData({dialogVisible: false})
            }, 3000)
          }
        }
      }
    }, 400)
  },
  // 判断内容是否可视
  getAbleView(){
    let currentMenuItem = wx.getStorageSync('currentMenuItem');
    if (this.data._globalData.token) {
      if (currentMenuItem['needPay']) {
        if (this.data.userInfo.activated) {
          return this.data._globalData.userService && ['progress', 'expire', 'expiring'].includes(this.data._globalData.userService.state);
        } else {
          return false;
        }
      } else {
        return true;
      }
    } else {
        return !currentMenuItem['needPay'];
    }
  },
  getModalContent(){
    let obj = {title: null, content: null};
    let userService = wx.getStorageSync('userService');
    if (userService) {
      if (userService.state === 'apply') {
        obj.title = '行情数据为收费服务';
        obj.content = '新客户可申请7天免费试用';
      } else if (userService.state === 'checking') {
        obj.title = '7天免费试用申请成功';
        obj.content = '审核通过后服务自动开通，请等待后台审核。';
      } else if (userService.state === 'start') {
        obj.title = '您订购的数据服务待生效';
        obj.content = `生效日期：${userService.openDate}~${userService.endDate}<br/>如有疑问，请联系客服。`;
      } else if (userService.state === 'expire') {
        obj.title = '您订购的数据服务将过期';
        obj.content = '为了不影响您的正常使用，请及时联系客服续约。';
      } else if (userService.state === 'expiring') {
        obj.title = '您订购的数据服务马上过期';
        obj.content = '为了不影响您的正常使用，请及时联系客服续约。';
      } else if (userService.state === 'expired') {
        obj.title = '您订购的数据服务已过期';
        obj.content = '行情数据服务：600元/年<br/>如需继续使用，请联系客服续约。';
      }
      this.setData({
        modalContent: obj
      })
    }
  },
  // 根据报价单id查询自定义表头
  getGroupColumnListByQuoteGroupId(_quoteGroupId){
    QuoteApi.getGroupColumnListByQuoteGroupId({quoteGroupId: _quoteGroupId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (res.data.length > 0) {
          let diyColumns = [];
          let selectedColumn = {label: "自选", prop: "collectTime"};
          diyColumns.push(selectedColumn);
          res.data.forEach(item=>{
            let column = {label: item.groupColumnName, prop: item.attributeValue};
            if (['lowestPrice','highestPrice','averagePrice','upsDowns','price','priceRange'].includes(item.attributeValue)) { column.align = 'right'; }
            diyColumns.push(column)
          })
          this.setData({
            ['tableInfo.columns']: diyColumns
          })
        } else {
          this.setData({
            ['tableInfo.columns']: quotationColumns
          })
        }
        this.getFrontQuoteGroup(_quoteGroupId)
      } else {
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/quotation/index', 'link')
        }
      }
    })
  },
  // 获取报价单数据
  getFrontQuoteGroup(_quoteGroupId){
    QuoteApi.getFrontQuoteGroup({quoteGroupId: _quoteGroupId}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (res.data && res.data.list) {
          res.data.list.forEach(item=>{
            if (item.quoteType == 'fixed') {
              item.price = item.averagePrice;
            }
            if (item.commodity) {
              item.commodityId = item.commodity.commodityId;
              item.commodityNo = item.commodity.commodityNo;
              item.commodityName = item.commodity.commodityName;
            }
            if (item.commodity && item.commodity.attributes.length>0) {
              item.commodity.attributes.forEach(sub=>{
                item[sub.attributeId] = sub.attributeValue;
              })
            }
            if (item.averagePrice) {item.averagePrice = Number(item.averagePrice)}
            if (item.highestPrice) {item.highestPrice = Number(item.highestPrice)}
            if (item.lowestPrice) {item.lowestPrice = Number(item.lowestPrice)}
            if (item.upsDowns) {item.upsDowns = Number(item.upsDowns)}
            if (item.quoteUnit) {item.quoteUnit = util.quoteUnitFilter(item.quoteUnit)}
            if (item.quoteDate) {item.quoteDate_MD = util.formatDate(item.quoteDate, 'MM-DD')}
            item.invoiceTax = util.invoiceTaxFilter(item.invoiceTax)
          })
          this.setData({
            ['tableInfo.data']: res.data.list
          })
        } else {
          this.setData({
            ['tableInfo.data']: []
          })
        }
      }
    })
  },
  // 添加或取消自选
  followQuote(_quoteId){
    QuoteApi.followQuote({quoteId: _quoteId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.showToast({icon: 'success', title: res.errMsg})
        this.getGroupColumnListByQuoteGroupId(this.data.currentQuoteGroupId)
      } else {
        wx.showToast({icon: 'error', title: res.errMsg})
        if (res.errCode == '999901') {
          commonUtil.handleTokenExpire('/packageA/pages/quotation/index', 'link')
        }
      }
    })
  },
  // 菜单点击
  menuClick(e){
    let level = e.currentTarget.dataset.level;
    let currentItem = e.currentTarget.dataset.item;
    // console.log(currentItem);

    if (this.data.ableView) {
      query.select("#table-area").scrollLeft = 0;
      query.select("#level2").scrollLeft = 0;
    }
    if (level == 1) {
      this.setData({
        currentMenu: currentItem,
        subList: currentItem.children,
      })

      if (currentItem.children.length > 0) {
        this.setData({ currentSub: currentItem.children[0] })

        if (currentItem.children[0].quoteGroupId) {
          this.setData({currentQuoteGroupId: currentItem.children[0].quoteGroupId})
          if (this.data.ableView) {
            this.getGroupColumnListByQuoteGroupId(currentItem.children[0].quoteGroupId)
          }
        } else {
          this.setData({
            currentQuoteGroupId: null,
            ['tableInfo.data']: []
          })
        }
      } else {
        this.setData({ currentSub: null })
        if (currentItem.quoteGroupId) {
          this.setData({currentQuoteGroupId: currentItem.quoteGroupId});
          if (this.data.ableView) {
            this.getGroupColumnListByQuoteGroupId(currentItem.quoteGroupId)
          }
        } else {
          this.setData({
            currentQuoteGroupId: null, 
            ['tableInfo.data']: []
          })
        }
      }
    } else if (level == 2) {
      this.setData({currentSub: currentItem});

      if (currentItem.quoteGroupId) {
        this.setData({currentQuoteGroupId: currentItem.quoteGroupId})
        if (this.data.ableView) {
          this.getGroupColumnListByQuoteGroupId(currentItem.quoteGroupId)
        }
      } else {
        this.setData({
          currentQuoteGroupId: null, 
          ['tableInfo.data']: []
        })
      }
    }
  },
  // 查询报价详情
  checkQuoteDetail(e){
    let currentItem = e.currentTarget.dataset.item;
    console.log(currentItem);
    if (this.data._globalData.token) {
      if (currentItem.quoteDate) {
        wx.removeStorageSync('currentQuote')
        wx.setStorageSync('currentMenu', this.data.currentMenu)
        if (this.data.currentSub) {
          wx.setStorageSync('currentSub', this.data.currentSub)
        }
        setTimeout(()=>{
          wx.setStorageSync('currentQuote', currentItem)
          wx.navigateTo({
            url: '/packageA/pages/quoteDetail/index',
          })
        }, 200)
      } else {
        wx.showToast({
          icon: 'none',
          title: '选定日期没有报价数据',
        })
      }
    } else {
      this.setData({dialogVisible: true})
      setTimeout(()=>{
        this.setData({dialogVisible: false})
      }, 3000)
    }
  },
  // 订阅操作
  toSave(e){
    let currentItem = e.currentTarget.dataset.item;
    if (this.data._globalData.token) {
      commonUtil.getUserServiceState();
      if (this.data._globalData.userService && ['progress', 'expire', 'expiring'].includes(this.data._globalData.userService.state)) {
        this.followQuote(currentItem.quoteId)
      } else {
        this.setData({dialogVisible: true})
        setTimeout(()=>{
          this.setData({dialogVisible: false})
        }, 3000)
      }
    } else {
      this.setData({dialogVisible: true})
      setTimeout(()=>{
        this.setData({dialogVisible: false})
      }, 3000)
      // wx.showToast({icon: 'none', title: '请先登录'})
      // setTimeout(()=>{
      //   this.redirectCurrent();
      // }, 2000)
    }
  },
  // 登录后跳转回当前页
  redirectCurrent(){
    wx.removeStorageSync('token')
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('userService')
    wx.removeStorageSync('tokenExpire')
    setTimeout(()=>{
      wx.redirectTo({
        url: '/packageA/pages/login/index?redirect_uri=/packageA/pages/quotation/index&redirect_uri_type=link',
      })
    }, 200)
  },
  // 登录操作
  toLogin(){
    this.redirectCurrent();
  },
  // 申请操作
  toApply(){
    UserApi.applyMemberServiceOrder().then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.showToast({icon: 'success', title: "申请数据试用成功"})
      } else {
        wx.showToast({icon: 'error', title: res.errMsg})
      }
    })
  },
  // 查询前端页面位置配置
  getFrontPageLocationList(){
    InfoApi.getFrontPageLocationList({pageId: '1713818862842454017'}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        res.data.forEach(item=>{
          if (item.componentType == 'menu_group') {
            this.getFrontMenuGroupList('1713818862842454017', item.locationId);
          }
        })
      }
    })
  },
  // 前端查询菜单云组件
  getFrontMenuGroupList(pageId, locationId){
    InfoApi.getFrontMenuGroupList({pageId: pageId, locationId: locationId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.setStorageSync('menuGroupList', res.data[0].itemList)
      }
    })
  },
  // 前端菜单查询
  getFrontMenuList(_menuId){
    QuoteApi.getFrontMenuList({menuId: _menuId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.setStorageSync('currentMenuItemList', res.data)
      }
    })
  },
  getCustomerService(){
    this.setData({customerDialogVisible: true})
  },
  closeCSModal(){
    this.setData({customerDialogVisible: false})
  },

  onShareAppMessage() {
    let _currentMenuItem = wx.getStorageSync('currentMenuItem');
    let paths;
    console.log(this.data.currentMenu);
    console.log(this.data.subList);
    console.log(this.data.currentSub);
    if (this.data.currentSub) {
      paths = "/packageA/pages/quotation/index?currentMenuItemId="+_currentMenuItem.menuId+"&currentMenuId="+this.data.currentMenu.menuId+"&currentSubId="+this.data.currentSub.menuId+"&currentQuoteGroupId="+this.data.currentQuoteGroupId;
    } else {
      paths = "/packageA/pages/quotation/index?currentMenuItemId="+_currentMenuItem.menuId+"&currentMenuId="+this.data.currentMenu.menuId+"&currentQuoteGroupId="+this.data.currentQuoteGroupId;
    }
    return {
      title: _currentMenuItem.itemName,
      path: paths,
    }
  },

  onShareTimeline() {
    let _currentMenuItem = wx.getStorageSync('currentMenuItem');
    let querys;
    if (this.data.currentSub) {
      querys = "currentMenuItemId="+_currentMenuItem.menuId+"&currentMenuId="+this.data.currentMenu.menuId+"&currentSubId="+this.data.currentSub.menuId+"&currentQuoteGroupId="+this.data.currentQuoteGroupId;
    } else {
      querys = "currentMenuItemId="+_currentMenuItem.menuId+"&currentMenuId="+this.data.currentMenu.menuId+"&currentQuoteGroupId="+this.data.currentQuoteGroupId;
    }
    return {
      title: _currentMenuItem.itemName,
      query: querys
    }
  }
})
